package com.crois.barrier.common.factory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author Hou Ze Yu
 * @description barrier 线程工厂
 * @date 2020/7/7
 */
public final class BarrierThreadFactory implements ThreadFactory {
    private static final AtomicLong THREAD_NUMBER =new AtomicLong(1);

    private static final ThreadGroup THREAD_GROUP = new ThreadGroup("barrier");

    private final boolean daemon;

    private final String namePrefix;

    public BarrierThreadFactory(final boolean daemon, final String namePrefix) {
        this.daemon = daemon;
        this.namePrefix = namePrefix;
    }

    public static  ThreadFactory threadCreate(final String namePrefix ,final boolean daemon){
        return new BarrierThreadFactory(daemon,namePrefix);
    }

    @Override
    public Thread newThread(Runnable runnable) {
        Thread thread =new Thread(THREAD_GROUP,runnable,
                THREAD_GROUP.getName()+"-"+namePrefix+"-"+THREAD_NUMBER.getAndIncrement());
        thread.setDaemon(daemon);
         if (thread.getPriority()!=Thread.NORM_PRIORITY){
            thread.setPriority(Thread.NORM_PRIORITY);
         }
        return thread;
    }

}
